<?php

/**
 * descript:
 * User: blue
 * Date: 2018/5/22 11:05
 */

namespace app\api\service;

use app\lib\exception\CateException;
use app\lib\exception\WxException;
use think\Exception;
use app\api\model\User as UserModel;

class UserToken extends Token
{
    protected $code;
    protected $wxAppId;
    protected $wxAppSecrete;
    protected $wxloginUrl;

    public function __construct($code='')
    {
        $this->wxAppId=config('weixin.app_id');
        $this->wxAppSecrete=config('weixin.app_secret');
        $s=config('weixin.openid_url');
        $this->wxloginUrl=sprintf($s,$this->wxAppId,$this->wxAppSecrete,$code);
    }

    /**
     * 获取token
     * @return string
     * @throws CateException
     * @throws Exception
     * @throws WxException
     */
    public function getToken(){
        //  获取openId
        $openId=curl_request($this->wxloginUrl);
        $openIdArr=json_decode($openId,true);
        if(empty($openIdArr)){
            throw new Exception('获取openId异常,微信内部错误');
        }else{
            if(array_key_exists('errcode',$openIdArr)){
                //    抛出异常
                throw new WxException([
                    'msg'=>$openIdArr['errmsg'],
                    'errCode'=>$openIdArr['errcode']
                ]);
            }else{
                //
                return $this->openId2Token($openIdArr);
            }
        }
    }

    /**
     * openid token 写入缓存
     * @param $wx
     * @return string
     * @throws CateException
     */
    private function openId2Token($wx){
        $openid=$wx['openid'];
        //调用模型判断openid是否存在
        $res=UserModel::findOpenId($openid);
        if(!$res){
            $user=UserModel::create([
              'openid'=>$openid
            ]);
            $uid=$user->id;
        }else{
            $uid=$res->id;
        }
        //生态token码
        $token=$this->produceToken();
        //写入缓存前的准备
        $result=$wx;
        $result['uid']=$uid;
        $result['scope']=16;
        $resultJ=json_encode($result);
        $expire=config('security.token_expire');
        //信息写入缓存中
        $cacheRes=cache($token,$resultJ,$expire);
        if(!$cacheRes){
        // 抛出异常
            throw new CateException([
               'msg'=>'服务器缓存异常',
               'errCode'=>1005
            ]);
        }
        return $token;
    }

    /**
     * 根据tokenid获取uid
     * @return mixed
     */
    public static function tokenGetUid(){
        $uid=self::tokenGetInfo('uid');
        return $uid;
    }


}